package com.jiyinit.web.core.business.service;

import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.web.core.business.dao.TabCoreFunDao;
import com.jiyinit.web.core.business.dao.TabCoreOrgDao;
import com.jiyinit.web.core.business.dao.TabFunRoleRelationDao;
import com.jiyinit.web.core.business.dao.TabOrgFunDao;
import com.jiyinit.web.core.business.dto.FunRolePageRequest;
import com.jiyinit.web.core.business.dto.FunctionPageRequest;
import com.jiyinit.web.core.business.entity.TabCoreOrgEntity;
import com.jiyinit.web.core.business.entity.TabOrgFunEntity;
import com.jiyinit.web.core.business.vo.FunctionVo;
import com.jiyinit.web.core.common.util.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lr on 2017/12/25.
 */
@Service("core.orgFunServiceImpl")
public class OrgFunctionServiceImpl {

    @Resource(name = "core.tabCoreFunDao")
    private TabCoreFunDao tabCoreFunDao;

    @Resource(name ="core.tabCoreOrgDao")
    private TabCoreOrgDao tabCoreOrgDao;

    @Resource(name = "core.tabOrgFunDao" )
    private TabOrgFunDao tabOrgFunDao;

    @Resource(name = "core.tabFunRoleRelationDao")
    private TabFunRoleRelationDao tabFunRoleRelationDao;

    public PagingResult<FunctionVo> findByPage(Integer orgId, FunctionPageRequest functionPageRequest){
        Integer parentId = tabCoreOrgDao.getTopParentOrgId(orgId);
        return tabCoreFunDao.findOrgByPage(parentId,functionPageRequest);
    }

    public List<FunctionVo> findFunction(Integer orgId){
        return tabCoreFunDao.findFunction(orgId);
    }

    public int update(Integer orgId,Integer[] funIds){
        Integer userId = UserUtil.getCurrentUser().getUserId();
        //查找原来的此机构下的权限
        List<TabOrgFunEntity> list = tabOrgFunDao.findFunctionByOrg(orgId);
        List<Integer> deleteIds = new ArrayList<>();
        for(TabOrgFunEntity entity : list){
            boolean isexsit = false;
            for (int i = 0; i <funIds.length ; i++) {
                if(entity.getFunId() ==funIds[i] ) {isexsit = true;break;}
            }
            if(!isexsit) deleteIds.add(entity.getFunId());
        }
        if(deleteIds!= null && deleteIds.size()>0){
            tabFunRoleRelationDao.deleteRel(orgId, userId,deleteIds);
        }
        //删除原来
        tabOrgFunDao.delete(orgId,userId);
        //增加现在
       int num = tabOrgFunDao.bacthsave(orgId,funIds,userId);
        return num;
    }


}
